import { contextBridge, ipcRenderer } from "electron";
import { useLoading } from "./utils/loading";
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
  return new Promise(resolve => {
    if (condition.includes(document.readyState)) {
      resolve(true)
    } else {
      document.addEventListener('readystatechange', () => {
        if (condition.includes(document.readyState)) {
          resolve(true)
        }
      })
    }
  })
}


// 暴露应用操作到主世界 暴露版本信息到主世界
contextBridge.exposeInMainWorld('appElectronAPI', {
  // 日志
  logger: (level: string, content: string) => ipcRenderer.invoke('logger', level, content),
  appVersion: (): Promise<string> => ipcRenderer.invoke('appVersion'),
  appQuit: (): Promise<void> => ipcRenderer.invoke('appQuit'),
  appRestart: (): Promise<void> => ipcRenderer.invoke('appRestart'),
  openDevTools: (): Promise<void> => ipcRenderer.invoke('openDevTools'),
  toggleDevTools: (): Promise<void> => ipcRenderer.invoke('toggleDevTools'),
  miniWindow: (): Promise<void> => ipcRenderer.invoke('miniWindow'),
  maxWindow: (): Promise<void> => ipcRenderer.invoke('maxWindow'),
  scaleWindow: (): Promise<void> => ipcRenderer.invoke('scaleWindow'),
  closeWindow: (): Promise<void> => ipcRenderer.invoke('closeWindow'),
  hideWindow: (): Promise<void> => ipcRenderer.invoke('hideWindow'),
  activeWindow: (): Promise<void> => ipcRenderer.invoke('activeWindow'),
  forceCloseWindow: (cfg: any): Promise<void> => ipcRenderer.invoke('forceCloseWindow', cfg),
  openLink: (url: string): Promise<void> => ipcRenderer.invoke('openLink', url),
  getUserDataPath: (): string => ipcRenderer.sendSync('getUserDataPath'),
  getTempPath: (): string => ipcRenderer.sendSync('getTempPath'),
  getDownloadsPath: (): string => ipcRenderer.sendSync('getDownloadsPath'),
  getLogsPath: (): string => ipcRenderer.sendSync('getLogsPath'),
  getCrashPath: (): string => ipcRenderer.sendSync('getCrashPath'),
  getAutoImport: (): string => ipcRenderer.sendSync('getAutoImport'),
  getBuildVersion: (): string => ipcRenderer.sendSync('getBuildVersion'),
  getArch: (): string => process.arch,
  getPlatform: (): string => process.platform,
  getVersionNode: (): string => process.versions.node,
  getVersionChrome: (): string => process.versions.chrome,
  getVersionElectron: (): string => process.versions.electron,
  install: (filePath: string): Promise<void> => ipcRenderer.invoke('install', filePath),
  hotUpdate: (version: string, hotUrl: string, diffUrl: string): Promise<void> => ipcRenderer.invoke('hotUpdate', version, hotUrl, diffUrl),
  openFile: (filePath: string): Promise<void> => ipcRenderer.invoke('openFile', filePath),
  cancelQuit: (): Promise<void> => ipcRenderer.invoke('cancelQuit'),
  sendMessage: (...args: any[]): void => ipcRenderer.send(...args),
  initAutoImport: (taskList: any[]): Promise<void> => ipcRenderer.invoke('initAutoImport', taskList),
  doCrash: (): Promise<void> => ipcRenderer.invoke('doCrash'),
  getRemoteText: (url: string, headers: Record<string, string> = {}): Promise<string> => ipcRenderer.invoke('getRemoteText', url, headers),
  onMessage: (channel: string, func: (...args: any[]) => void): (() => void) => {
    const listener = (event: IpcRendererEvent, ...args: any[]) => func(...args);
    ipcRenderer.on(channel, listener);
    return () => {
      ipcRenderer.removeListener(channel, listener);
    };
  },
});

// 增加loading效果
// ----------------------------------------------------------------------
const { appendLoading, removeLoading } = useLoading();
domReady().then(appendLoading);
window.onmessage = ev => {
  ev.data.payload === 'removeLoading' && removeLoading()
};
setTimeout(removeLoading, 2000);
// ----------------------------------------------------------------------
declare global {
  interface Window {
    electronAPI?: any;
    appVersion: () => Promise<string>;
    appQuit: () => Promise<void>;
    appRestart: () => Promise<void>;
    openDevTools: () => Promise<void>;
    toggleDevTools: () => Promise<void>;
    miniWindow: () => Promise<void>;
    maxWindow: () => Promise<void>;
    scaleWindow: () => Promise<void>;
    closeWindow: () => Promise<void>;
    hideWindow: () => Promise<void>;
    activeWindow: () => Promise<void>;
    forceCloseWindow: (cfg: any) => Promise<void>;
    openLink: (url: string) => Promise<void>;
    getUserDataPath: () => string;
    getTempPath: () => string;
    getDownloadsPath: () => string;
    getLogsPath: () => string;
    getCrashPath: () => string;
    getAutoImport: () => string;
    getBuildVersion: () => string;
    getArch: () => string;
    getPlatform: () => string;
    install: (filePath: string) => Promise<void>;
    hotUpdate: (version: string, hotUrl: string, diffUrl: string) => Promise<void>;
    openFile: (filePath: string) => Promise<void>;
    cancelQuit: () => Promise<void>;
    sendMessage: (...args: any[]) => void;
    initAutoImport: (taskList: any[]) => Promise<void>;
    doCrash: () => Promise<void>;
    getRemoteText: (url: string, headers?: Record<string, string>) => Promise<string>;
    onMessage: (channel: string, func: (...args: any[]) => void) => () => void;
  }
}

// 监听 DOMContentLoaded 事件并更新页面上的版本信息
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector: string, text: string) => {
    const element = document.getElementById(selector);
    if (element) element.innerText = text;
  };
  const listVersion = ['chrome', 'node', 'electron'];
  listVersion.forEach((dependency) => {
    replaceText(`${dependency}-version`, process.versions[dependency]);
  })
});